package com.hk.web.dto.article;

import com.hk.commons.enums.ArticleStatus;
import com.hk.commons.enums.ArticleType;
import com.hk.web.domain.entity.Article;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Antinomy on 17/1/10.
 */
public class ArticleSpecification {

    public static Specification<Article> buildFromDTO(ArticleQueryDTO dto) {
        return (root, query, builder) -> {

            ArrayList<Predicate> list = new ArrayList<>();

            list.add(builder.notEqual(root.<ArticleStatus>get("status"), ArticleStatus.DELETED));

            if (dto.getType() != null) {
                list.add(builder.equal(root.<ArticleType>get("type"), dto.getType()));
            } else {

                List<ArticleType> typeList = new ArrayList<>();
                typeList.add(ArticleType.FOCUS_VIEW);
                typeList.add(ArticleType.WEALTH_REPORT);
                typeList.add(ArticleType.WEALTH_SCHOOL);
                typeList.add(ArticleType.WEEKLY_VIEW);

                Expression<ArticleType> exp =root.<ArticleType>get("type");
                list.add(exp.in(typeList));
            }

            if (dto.getDateStart() != null && dto.getDateEnd() != null) {
                list.add(builder.between(root.<Date>get("eventDate"), dto.getDateStart(), dto.getDateEnd()));
            }

            if (StringUtils.isNoneBlank(dto.getKeyword())) {
                list.add(builder.like(root.<String>get("title"), "%"+dto.getKeyword()+"%"));
            }


            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);

            return builder.and(predicates);
        };
    }
}
